/*
 * Debug serial output module for Flying Fox
 *
 * by Zik Saleeba 2008-03-31
 */

#include <stdarg.h>
#include <stdio.h>
#include <string.h>

#include "ffox.h"
#include "serial.h"
#include "dbgprintf.h"


/* maximum length of a debug message */
#define MESSAGE_MAX 256
#define max(x,y) (((x)>(y))?(x):(y))
    
/* module variables */
static char Message[MESSAGE_MAX];
static xSemaphoreHandle DebugLock;


/*
 * NAME:        dbgprintf_Init
 * ACTION:      Initialise the debugging system
 */
 
void dbgprintf_Init()
{
    DebugLock = xSemaphoreCreateMutex();
}


/*
 * NAME:        vdbgprintf
 * ACTION:      Debugging vprintf. Sends output to the serial radio interface
 */
 
void vdbgprintf(const char *format, va_list args)
{
    int MessageLength;
    
    /* lock access to the buffer */
    if (xSemaphoreTake(DebugLock, portMAX_DELAY) != pdTRUE)
        return;
    
    /* output the message */
    MessageLength = vsnprintf(Message, MESSAGE_MAX, format, args);
    if (MessageLength > 0)
    {
        if (MessageLength > MESSAGE_MAX-1)
            MessageLength = MESSAGE_MAX-1;
            
        Serial_Write(RADIO_PORT,  Message, MessageLength, -1);
    }
    
    /* release our lock on the hardware */
    xSemaphoreGive(DebugLock);
}


/*
 * NAME:        dbgprintf
 * ACTION:      Debugging printf. Sends output to the serial radio interface
 */
 
void dbgprintf(const char *format, ...)
{
    va_list args;
    
    va_start(args, format);
    vdbgprintf(format, args);
}


/*
 * NAME:        trace_LOG
 * ACTION:      Debugging printf. Sends output to the serial radio interface
 */
 
void trace_LOG(enum trace_level level, const char *format, ...)
{
    va_list args;
    
    va_start(args, format);
    vdbgprintf(format, args);
}


/*
 * NAME:        dbgprintd
 * ACTION:      Print a "double" to a few decimal places precision
 * PARAMETERS:  double Num - the number to print
 */
 
void dbgprintd(double Num)
{
    char Sign[2];
    
    if (Num < 0)
    {
        Num = -Num;
        strcpy(Sign, "-");
    }
    else
        Sign[0] = '\0';
    
    dbgprintf("%s%d.%04d", Sign, (int)Num, (int)(Num*10000.0) - ((int)Num * 10000));
}
